package user

import (
	"context"
	"strings"

	"mall/service/backend/api/internal/svc"
	"mall/service/backend/api/internal/types"
	"mall/service/backend/common/enum/errorcode"
	"mall/service/backend/common/errorx"
	"mall/service/backend/rpc/backendclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateUserLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUpdateUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateUserLogic {
	return &UpdateUserLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UpdateUserLogic) UpdateUser(req *types.UpdateSystemUserReq) (resp *types.BaseMsgResp, err error) {
	if req.Username != nil && len(strings.TrimSpace(*req.Username)) == 0 {
		return nil, errorx.NewCodeError(errorcode.InvalidArgument,
			l.svcCtx.Trans.Trans(l.ctx, "user.usernameRequired"))
	}

	if req.Password != nil && len(strings.TrimSpace(*req.Password)) == 0 {
		return nil, errorx.NewCodeError(errorcode.InvalidArgument,
			l.svcCtx.Trans.Trans(l.ctx, "user.passwordRequired"))
	}

	res, err := l.svcCtx.BackendRpc.UpdateUser(l.ctx, &backendclient.UserInfo{
		Id:           req.Id,
		Username:     req.Username,
		Password:     req.Password,
		Nickname:     req.Nickname,
		Avatar:       req.Avatar,
		Description:  req.Description,
		HomePath:     req.HomePath,
		Mobile:       req.Mobile,
		Email:        req.Email,
		Status:       req.Status,
		DepartmentId: req.DepartmentId,
		PositionIds:  req.PositionIds,
		RoleIds:      req.RoleIds,
	})
	if err != nil {
		return
	}

	return &types.BaseMsgResp{
		Success: true,
		Msg:     l.svcCtx.Trans.Trans(l.ctx, res.Msg),
	}, nil
}
